<?php

namespace App\Store\Models\Wxapp;

use App\Common\Services\Common;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Member\Member;

class WxappCouponCodeList extends Model
{
    protected $table = 'site_wxapp_coupon_code_list';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    public static function getList(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['meminfo'])->where(['cp_id' => $cp_id])->orderBy('exchange_at', 'desc');
        $is_used=intval($request->is_used);
        if($is_used>0){
            $query->where('is_used',$is_used);
        }

        $coupon_id=intval($request->coupon_id);
        if($coupon_id>0){
            $query->where('coupon_id',$coupon_id);
        }

        //是否兑换
        $is_exchange=intval($request->is_exchange);
        if($is_exchange==1){
            $query->where('mem_id',0);
        }else{

            $query->where('mem_id','>',0);
        }


        $start_time = strtotime($request->start_time) > 0 ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = strtotime($request->end_time) > 0 ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $query->where('exchange_at', '>=', $start_time)->where('exchange_at', '<=', $end_time);
        }


        $is_lose=intval($request->is_lose);
        if($is_lose>0){
            if($is_lose==1){//未失效
                $query->where('available_end_time','>=',time());
            }

            if($is_lose==2){//已失效
                $query->where('available_end_time','<',time());
            }

        }
        $limit = $request->limit ?? 10;
        $list = $query->paginate($limit)->toArray();
        return Common::paginateDataToArray($list);
    }


    /**
     *获取列表
     */
    public static function getListByMem(Request $request,$cp_id,$mem_id)
    {

        $query = self::where(['cp_id' => $cp_id,'mem_id'=>$mem_id,'is_receive'=>2])->orderBy('exchange_at', 'desc');
        $is_used=intval($request->is_used);
        if($is_used>0){
            $query->where('is_used',$is_used);
        }
        $is_lose=intval($request->is_lose);
        if($is_lose>0){
            if($is_lose==1){//未失效
                $query->where('available_end_time','>=',time());
            }

            if($is_lose==2){//已失效
                $query->where('available_end_time','<',time());
            }

        }
        $limit = $request->limit ?? 10;
        $list = $query->paginate($limit)->toArray();
        return Common::paginateDataToArray($list);
    }

    public  function meminfo(){
        return $this->hasOne(Member::class, 'id', 'mem_id')->where('is_del',1);
    }
}
